package jp.tuyano.helo.client;

import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class Helo implements EntryPoint {

    private static final String SERVER_ERROR = "SERVER ERROR!!";

    private final HeloServiceAsync heloService = GWT
        .create(HeloService.class);

    private FlexTable panel;
    private Label label;

    public void onModuleLoad() {
        label = new Label("please wait...");
        RootPanel.get("helo_label").add(label);
        this.sendToServer();
    }

    public void sendToServer() {
        heloService.getAllEntities(new AsyncCallback<List<MyDataObject>>() {

            public void onSuccess(List<MyDataObject> result) {
                if (!result.isEmpty()) {
                    FlexTable record = new FlexTable();
                    record.setBorderWidth(1);
                    record.setText(0, 0, "ID");
                    record.setText(0, 1, "name");
                    record.setText(0, 2, "mail");
                    record.setText(0, 3, "tel");
                    record.setText(0, 4, "memo");
                    for (int i = 0; i < result.size(); i++) {
                        MyDataObject data = result.get(i);
                        record.setText(i+1 ,0, String.valueOf(data.getId()));
                        record.setText(i+1, 1, data.getName());
                        record.setText(i+1, 2, data.getMail());
                        record.setText(i+1, 3, data.getTel());
                        record.setText(i+1, 4, data.getMemo());
                    }
                    if (panel != null) {
                        RootPanel.get("helo_panel").remove(panel);
                    }
                    panel = record;
                    RootPanel.get("helo_panel").add(panel);
                    label.setText("Personal Data List.");
                }
            }

            public void onFailure(Throwable caught) {
                label.setText(SERVER_ERROR);
            }
        });
    }

}